package sk.kainitram.fuel;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainFuelActivity extends Activity  {
	private final int NEW_CAR=1;
	private final int NEW_FUEL=2;
	private final String TAB_SELECTED_INDEX = "TAB_SELECTED_INDEX";
	private int mOrientation;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        
		setContentView(R.layout.main);
		initTitle();		
		createTabControl();
		
		initActionBar(savedInstanceState);
    }
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }  
    
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      
      ActionBar actionBar = getActionBar();      
      savedInstanceState.putInt(TAB_SELECTED_INDEX, actionBar.getSelectedNavigationIndex());      
    }         
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
        	case R.id.menu_new_fuel:
        	{        		
                showNewFuelActivity();
                return true;
        	}
        	case R.id.menu_undo:
        	{
        		Toast toast = Toast.makeText(this, "Prebehlo Undo", Toast.LENGTH_SHORT);
        		toast.show();
        		
        		return true;
        	}
        	case R.id.menu_new_car:
        	{
        		showNewCarActivity();
        		return true;
        	}
        	case R.id.menu_settings:
        	{
        		AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Prvy message box")
                	.setCancelable(false)
                	.setPositiveButton("Ano", new DialogInterface.OnClickListener() {
        				
        				public void onClick(DialogInterface dialog, int which) {
        					
        				}
        			})
        			.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
        				
        				public void onClick(DialogInterface dialog, int which) {
        					dialog.cancel();
        				}
        			});
                
                AlertDialog alert = builder.create();
                alert.show();
                
                return true;
        	}
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == NEW_CAR) {
            if (resultCode == RESULT_OK) {
           
            	Toast toast = Toast.makeText(this, "Auto bolo pridane", Toast.LENGTH_SHORT);
        		toast.show();
            }
            else
            {
            	Toast toast = Toast.makeText(this, "Bol stlaceny cancel", Toast.LENGTH_SHORT);
        		toast.show();
            }
        }
    }
    
    
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    
    
    public void onNewFuelClick(View view)
    {
    	showNewFuelActivity();
    }
    
    
    public void createTabControl()      
    {    
    	ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        Tab tab = actionBar.newTab()
                .setIcon(R.drawable.ic_tabs_overview)
                .setTabListener(new TabListener<OverviewActivity>(
                        this, "overview", OverviewActivity.class));
        checkAndSetTitle(tab, R.string.overview_caption);
        actionBar.addTab(tab, false);
    	        
        tab = actionBar.newTab()
                .setIcon(R.drawable.ic_tabs_statistics)
                .setTabListener(new TabListener<StatisticsActivity>(
                        this, "statistic", StatisticsActivity.class));
        checkAndSetTitle(tab, R.string.statistic_caption);
        actionBar.addTab(tab, false);
        
        tab = actionBar.newTab()
                .setIcon(R.drawable.ic_tabs_fuels)
                .setTabListener(new TabListener<FuelsActivity>(
                        this, "fuels", FuelsActivity.class));
        checkAndSetTitle(tab, R.string.fuels_caption);
        actionBar.addTab(tab, false);
        
        tab = actionBar.newTab()
                .setIcon(R.drawable.ic_tabs_cars)
                .setTabListener(new TabListener<CarsActivity>(
                        this, "cars", CarsActivity.class));
        checkAndSetTitle(tab, R.string.cars_caption);
        actionBar.addTab(tab, false);              
    }

    
	private void initActionBar(Bundle savedInstanceState) {
		
		int tabIndex = 0;
		if (savedInstanceState!=null) {
			tabIndex = savedInstanceState.getInt(TAB_SELECTED_INDEX);
		}
		
		ActionBar actionBar = getActionBar();
	    actionBar.setSelectedNavigationItem(tabIndex);	  
	}
 
	
    private void initTitle()
    {
    	mOrientation = getResources().getConfiguration().orientation;
		switch(mOrientation)
        {
	        case  Configuration.ORIENTATION_LANDSCAPE:
	            getActionBar().setDisplayShowTitleEnabled(false);
	            break;
	        case Configuration.ORIENTATION_PORTRAIT:
	        	getActionBar().setDisplayShowTitleEnabled(true);
	        	break;
        }
    }
    
    
    private void checkAndSetTitle(Tab tab, int titleResId)
    {
    	if (mOrientation == Configuration.ORIENTATION_PORTRAIT)
    	{
    		tab.setText(titleResId);
    	}
    }
    
    
    private void showNewCarActivity()
    {
    	 Intent newCar = new Intent();              
    	 newCar.setClass(this,NewCarActivity.class);
         startActivityForResult(newCar, NEW_CAR);
    }
    
    
    private void showNewFuelActivity()
    {
    	Intent newFuel = new Intent();              
    	newFuel.setClass(this,NewFuel.class);
        startActivityForResult(newFuel,NEW_FUEL);
    }
    
    
    private static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private Fragment mFragment;
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);        
        }

        /* The following are each of the ActionBar.TabListener callbacks */

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
        	// Check if the fragment is already initialized
            if (mFragment == null)
            {
                // If not, instantiate and add it to the activity
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else
            {
                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        	if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }   
    }
}